<template>
  <div>
    <el-card class="box-card">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="账户名" prop="loginName">
          <el-input v-model="ruleForm.loginName" disabled />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="ruleForm.nickname" />
        </el-form-item>
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="ruleForm.oldPassword" placeholder="请输入原密码" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="ruleForm.newPassword" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="类型" prop="region">
          <el-select v-model="ruleForm.region" placeholder="请选择类型">
            <el-option label="读者" value="reader" />
            <el-option label="管理员" value="manager" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { updateInfo } from '@/api/user'
import store from '@/store'
export default {
  data() {
    return {
      ruleForm: {
        nickname: '',
        region: '',
        oldPassword: '',
        newPassword: '',
        loginName: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      }
    }
  },
  async created() {
    const userinfo = await store.dispatch('user/getInfo')
    this.ruleForm.loginName = userinfo.user_name
    this.ruleForm.nickname = userinfo.nickname
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const result = await updateInfo(this.ruleForm)
          if (result.status === 0) {
            this.$message({
              type: 'success',
              message: '修改密码成功!'
            })
            this.ruleForm.oldPassword = ''
            this.ruleForm.newPassword = ''
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>
 .demo-ruleForm {
   width: 500px;
 }
 .box-card {
   margin: 30px;
 }
</style>
